/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package syslivros;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Rafael
 */
public class EntregaApostila extends javax.swing.JFrame {
 
    /**
     * Creates new form Cadastrar
     */
    public EntregaApostila() throws SQLException {
        initComponents();
        try {
                Conexao.conectar("root", "positivo");
                System.out.println("conetado!ура товарищи!");
                
            } catch (Exception ex) {
               JOptionPane.showMessageDialog(null,"Erro ao conectar ao banco"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
            } 
           
        try{PopulaComboCatis();
        }catch(SQLException ex){
        JOptionPane.showMessageDialog(this,"Erro ao carregar catis"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
        }
        try{PopulaComboCurso();
        }catch(Exception ex1){
        JOptionPane.showMessageDialog(this,"Erro ao carregar cursos" +ex1.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
           
        }
        try{PopulaComboProfessor();
        }catch(Exception ex){JOptionPane.showMessageDialog(this,"Erro ao carregar professor"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
        }
        }
         public void PopulaComboCatis()throws  SQLException{
String SQL="select NomeCatis  from Catis  ";
ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
   DefaultComboBoxModel model =(DefaultComboBoxModel) cbCatis.getModel();
   model.removeAllElements();
   while(rs.next()){
   model.addElement(rs.getString("NomeCatis"));
   }

}
         public void PopulaComboCurso()throws  SQLException{
String SQL="select NomeCurso  from listacursos  ";
ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
   DefaultComboBoxModel model =(DefaultComboBoxModel) cbApostila.getModel();
   model.removeAllElements();
   while(rs.next()){
   model.addElement(rs.getString("NomeCurso"));
   }

}
 public void PopulaComboProfessor()throws  SQLException{
String SQL="select Nome  from Professores  ";
ResultSet rs = Conexao.ConexaoJDBC.createStatement().executeQuery(SQL);
   DefaultComboBoxModel model =(DefaultComboBoxModel) cbProfessor.getModel();
   model.removeAllElements();
   while(rs.next()){
   model.addElement(rs.getString("Nome"));
   }

}   
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGrupo_Periodo = new javax.swing.ButtonGroup();
        btnVoltar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtDataEnvio = new javax.swing.JFormattedTextField();
        lblDataEnvio = new javax.swing.JLabel();
        lblApostila = new javax.swing.JLabel();
        cbApostila = new javax.swing.JComboBox();
        lblCatis = new javax.swing.JLabel();
        cbCatis = new javax.swing.JComboBox();
        lblQauntidadeApostilas = new javax.swing.JLabel();
        txtQtdApostilas = new javax.swing.JTextField();
        lblProfessor = new javax.swing.JLabel();
        cbProfessor = new javax.swing.JComboBox();
        rdBtn_manha = new javax.swing.JRadioButton();
        rdBtn_Tarde = new javax.swing.JRadioButton();
        rdBtn_Noite = new javax.swing.JRadioButton();
        lblManha = new javax.swing.JLabel();
        lblTarde = new javax.swing.JLabel();
        lblNoite = new javax.swing.JLabel();
        lbl_periodo = new javax.swing.JLabel();
        btnEntregar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Entregar Apostilas");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        btnVoltar.setText("Voltar");
        btnVoltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVoltarActionPerformed(evt);
            }
        });
        btnVoltar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnVoltarKeyPressed(evt);
            }
        });

        try {
            txtDataEnvio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        lblDataEnvio.setText("Data de envio: ");

        lblApostila.setText("Apostila: ");

        cbApostila.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione uma Apostila", ".NET Framework", "Java", "Linux", "Windows Server" }));

        lblCatis.setText("Catis: ");

        cbCatis.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione um Catis", "Centro Tecnológico (Sala 72)", "Centro Tecnológico (Sala 73)", "CECAP", "SETEC", "PROA", "Lúcio Martins", "Espaço da Juventude", "Sub Prefeitura (Lab. 1)", "Sub Prefeitura (Lab. 2)", "Saulo de Tarso" }));

        lblQauntidadeApostilas.setText("Quantidade de apostilas: ");

        lblProfessor.setText("Professor: ");

        cbProfessor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btnGrupo_Periodo.add(rdBtn_manha);
        rdBtn_manha.setText("M");

        btnGrupo_Periodo.add(rdBtn_Tarde);
        rdBtn_Tarde.setText("T");

        btnGrupo_Periodo.add(rdBtn_Noite);
        rdBtn_Noite.setText("N");

        lblManha.setText("- Manhã");

        lblTarde.setText("-Tarde");

        lblNoite.setText("-Noite");

        lbl_periodo.setText("Periodo: ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblDataEnvio)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDataEnvio, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblApostila)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblCatis)
                        .addGap(18, 18, 18)
                        .addComponent(cbCatis, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblQauntidadeApostilas)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtQtdApostilas, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblProfessor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbProfessor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rdBtn_manha)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblManha)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(rdBtn_Tarde)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblTarde)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(rdBtn_Noite)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblNoite))
                    .addComponent(lbl_periodo))
                .addContainerGap(68, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblApostila)
                    .addComponent(cbApostila, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCatis)
                    .addComponent(cbCatis, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblQauntidadeApostilas)
                    .addComponent(txtQtdApostilas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblDataEnvio)
                    .addComponent(txtDataEnvio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
                .addComponent(lbl_periodo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblManha)
                        .addComponent(lblTarde)
                        .addComponent(rdBtn_Noite)
                        .addComponent(lblNoite)
                        .addComponent(rdBtn_manha))
                    .addComponent(rdBtn_Tarde, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblProfessor, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cbProfessor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        btnEntregar.setText("Entregar");
        btnEntregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEntregarActionPerformed(evt);
            }
        });
        btnEntregar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btnEntregarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnEntregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 292, Short.MAX_VALUE)
                        .addComponent(btnVoltar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnVoltar)
                    .addComponent(btnEntregar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-464)/2, (screenSize.height-338)/2, 464, 338);
    }// </editor-fold>//GEN-END:initComponents

    private void btnVoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVoltarActionPerformed
        new Apostilas().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_btnVoltarActionPerformed

    private void btnVoltarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnVoltarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnVoltarActionPerformed(null);
        }
    }//GEN-LAST:event_btnVoltarKeyPressed

    private void btnEntregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntregarActionPerformed
//faça tbm que se gere um protocolo de recebimento da apostila 
         int apostilasTotal; 
          int qtApostilas_Atual = 0;
           String _char;
        
        if(!cbApostila.getSelectedItem().equals("Selecione uma Apostila")&&(!cbCatis.getSelectedItem().equals("Selecione um Catis"))
                &&!txtQtdApostilas.getText().equals("") && !txtQtdApostilas.getText().equals("0")&&!txtDataEnvio.getText().equals("  /  /    ")){
            
            try{
                String data=txtDataEnvio.getText();
                        
                int qtdApostila=Integer.valueOf(txtQtdApostilas.getText());
            char periodo;
            if(rdBtn_Noite.isSelected()){
            periodo='N';
            }else if(rdBtn_Tarde.isSelected()){
            periodo='T';
            }else{
            periodo='M';
            }
                System.out.println(periodo);
                String curso = (String) cbApostila.getSelectedItem();
                String catis = (String) cbCatis.getSelectedItem();
                String professor= (String) cbProfessor.getSelectedItem();
        
            switch (curso) {
                case ".NET":
                    
                       
                try {
                 PreparedStatement    p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Dotnet >=0 " );
               
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Dotnet");
            
       
        } apostilasTotal=qtApostilas_Atual-qtdApostila;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
                +"Catis: "+catis+"\n"
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
                +"Periodo: "+periodo+"\n"
                +"Professor:"+professor,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                       
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Dotnet = ? , dt_data_entrada = ?");
                        
                        ps.setInt(1, apostilasTotal);
                        
                        try {
                        ps.setString(2, SysLivros.DataPTtoENtoPT(data)); 
                    } catch (Exception ex) {
                       JOptionPane.showMessageDialog(this,"Erro ao cadastrar data estoque no curso 1 " +ex.getMessage());
                    }             //ajustar    
                                        
                        ps.execute();
                        PreparedStatement psinsert =Conexao.ConexaoJDBC.prepareStatement("insert into estoque_curso values(?,?,?,?,?,?)");
                        psinsert.setString(1, null);
                        psinsert.setString(2, curso);
                    
                        psinsert.setString(3, _char= String.valueOf(periodo));
                        psinsert.setInt(4, qtdApostila);
                        psinsert.setString(5,catis);
                       
                        try {
                        psinsert.setString(6, SysLivros.DataPTtoENtoPT(data));//erro
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data estoque no curso 2 " +ex.getMessage());
                    }
                        psinsert.execute();
                        
                         PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_curso values(?,?,?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                        ps_InsertHistorico.setString(3, _char=String.valueOf(periodo));
                        ps_InsertHistorico.setInt(4, qtdApostila);
                        ps_InsertHistorico.setString(5, catis);
                    
                        try {
                        ps_InsertHistorico.setString(6, SysLivros.DataPTtoENtoPT(data));
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this,"Erro ao cadastrar data no historico do curso 3 " +ex.getMessage());
                    }
                        ps_InsertHistorico.execute();
//                        try {
//                            SysLivros.geraRelatorio_ApostilasEnviadasDOC();
//                        } catch (FileNotFoundException ex) {
//                            Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
//                        }
          
                        JOptionPane.showMessageDialog(this, "Atualização feita com sucesso","Entrega de apostilas",JOptionPane.INFORMATION_MESSAGE);
            try {
                                SysLivros.geraReciboApostilaDOC(curso, catis, qtdApostila, data, periodo, professor);
                            } catch (FileNotFoundException ex) {
                                Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        new Apostilas().setVisible(true);
            this.dispose();}
                        
                         } catch (SQLException ex) {
                   
                 
                         } break;
                    
                case "Java":
                    try {
                        PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Java >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Java");
            
       
        }apostilasTotal=qtApostilas_Atual-qtdApostila;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
                +"Catis: "+catis+"\n"
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
                +"Periodo: "+periodo+"\n"
                +"Professor:"+professor,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Java = ? , dt_data_entrada = ?");
                                       
                        ps.setInt(1, apostilasTotal);                  
                             try{             
                      ps.setString(2, SysLivros.DataPTtoENtoPT(data));  //ajustar               
                             }catch(Exception ex){
                             JOptionPane.showMessageDialog(this,"Erro ao atualizar a data "+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                             }      
                        ps.execute();
                        PreparedStatement psinsert =Conexao.ConexaoJDBC.prepareStatement("insert into estoque_curso values(?,?,?,?,?,?)");
                        psinsert.setString(1, null);
                        psinsert.setString(2, curso);
                    
                        psinsert.setString(3, _char= String.valueOf(periodo));
                        psinsert.setInt(4, qtdApostila);
                        psinsert.setString(5,catis);
                          psinsert.setString(6, SysLivros.DataPTtoENtoPT(data));
                        psinsert.execute();

                       PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_curso values(?,?,?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                        ps_InsertHistorico.setString(3, _char=String.valueOf(periodo));
                        ps_InsertHistorico.setInt(4, qtdApostila);
                        ps_InsertHistorico.setString(5, catis);
                        ps_InsertHistorico.setString(6, SysLivros.DataPTtoENtoPT(data)); 
                        ps_InsertHistorico.execute();
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                            try {
                                SysLivros.geraReciboApostilaDOC(curso, catis, qtdApostila, data, periodo, professor);
                            } catch (FileNotFoundException ex) {
                                Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                    
                }   break;
                case "Linux":
                    try {
                        PreparedStatement p;
                    p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_Linux >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_Linux");
            
       
        }apostilasTotal=qtApostilas_Atual-qtdApostila;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
                +"Catis: "+catis+"\n"
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
                +"Periodo: "+periodo+"\n"
                +"Professor:"+professor,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_Linux = ? , dt_data_entrada = ?");
                                         
                        ps.setInt(1,apostilasTotal );                  
                                        
                       ps.setString(2,SysLivros.DataPTtoENtoPT(data));                  //ajustar
                                      
                        ps.execute();
                       PreparedStatement psinsert =Conexao.ConexaoJDBC.prepareStatement("insert into estoque_curso values(?,?,?,?,?,?)");
                        psinsert.setString(1, null);
                        psinsert.setString(2, curso);
                    
                        psinsert.setString(3, _char= String.valueOf(periodo));
                        psinsert.setInt(4, qtdApostila);
                        psinsert.setString(5,catis);
                        psinsert.setString(6, SysLivros.DataPTtoENtoPT(data));
                        psinsert.execute();
                        
                         PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into historico_curso values(?,?,?,?,?,?)");
                         ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                        ps_InsertHistorico.setString(3, _char=String.valueOf(periodo));
                        ps_InsertHistorico.setInt(4, qtdApostila);
                        ps_InsertHistorico.setString(5, catis);
                        ps_InsertHistorico.setString(6, SysLivros.DataPTtoENtoPT(data));
                        ps_InsertHistorico.execute();

                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                        try {
                                SysLivros.geraReciboApostilaDOC(curso, catis, qtdApostila, data, periodo, professor);
                            } catch (FileNotFoundException ex) {
                                Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados!"+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                
                }   break;
                case "Windows Server": //seguir o modelo  abaixo!!!!
                    try {
                        PreparedStatement p = Conexao.ConexaoJDBC.prepareStatement( "select * from estoque_base  where qt_WindowsServer >=0 " );
                       ResultSet rs=p.executeQuery();
        while(rs.next()){
            
           qtApostilas_Atual =rs.getInt("qt_WindowsServer");
            
       
        } apostilasTotal=qtApostilas_Atual-qtdApostila;
        if(JOptionPane.showConfirmDialog(this, "Verifique os dados antes de confirmar: \n"
                + "Apostila: "+curso+"\n"
                +"Catis: "+catis+"\n"
                +"Quantidade: "+qtdApostila+"\n"
                +"Data de Envio: "+data+"\n"
                +"Periodo: "+periodo+"\n"
                +"Professor:"+professor,"Confirmação",JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                        PreparedStatement ps = Conexao.ConexaoJDBC.prepareStatement("update estoque_base set qt_WindowsServer = ? , dt_data_entrada = ?");
                                        
                        ps.setInt(1, apostilasTotal);                 
                        ps.setString(2,SysLivros.DataPTtoENtoPT(data));                  
                                       
                        ps.execute();
                        PreparedStatement psinsert =Conexao.ConexaoJDBC.prepareStatement("insert into estoque_curso values(?,?,?,?,?,?)");
                        psinsert.setString(1, null);
                        psinsert.setString(2, curso);
                    
                        psinsert.setString(3, _char= String.valueOf(periodo));
                        psinsert.setInt(4,qtdApostila);
                        psinsert.setString(5,catis);
                        psinsert.setString(6,SysLivros.DataPTtoENtoPT(data));
                        psinsert.execute();
                        
                        PreparedStatement ps_InsertHistorico=Conexao.ConexaoJDBC.prepareStatement("insert into Historico_curso values(?,?,?,?,?,?)");
                        ps_InsertHistorico.setString(1, null);
                         ps_InsertHistorico.setString(2, curso);
                        ps_InsertHistorico.setString(3, _char=String.valueOf(periodo));
                        ps_InsertHistorico.setInt(4, qtdApostila);
                        ps_InsertHistorico.setString(5, catis);
                          ps_InsertHistorico.setString(6, SysLivros.DataPTtoENtoPT(data));
                        ps_InsertHistorico.execute();
                        JOptionPane.showMessageDialog(this, "Autualizado com sucesso", "Entrega", JOptionPane.INFORMATION_MESSAGE);
                        try {
                                SysLivros.geraReciboApostilaDOC(curso, catis, qtdApostila, data, periodo, professor);
                            } catch (FileNotFoundException ex) {
                                Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        new Principal().setVisible(true);
                        this.dispose();}
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(this, "Erro ao inserir dados! "+ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
                
                }   break;}
                      
           
            }
            catch(  NumberFormatException ex){
                lblQauntidadeApostilas.setForeground(Color.red);
            JOptionPane.showMessageDialog(this,"Digite apenas números inteiros"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
            
            }
            
            
            
        } else{ if(!rdBtn_Noite.isSelected()&&!rdBtn_Tarde.isSelected()&&!rdBtn_manha.isSelected()){
        
        JOptionPane.showMessageDialog(this,"Selecione um período!","ERRO",JOptionPane.ERROR_MESSAGE);
        lbl_periodo.setForeground(Color.red);
        }else{
        lbl_periodo.setForeground(Color.black);
        }
            
            if(cbApostila.getSelectedItem().equals("Selecione uma Apostila")) {
            JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Apostila\"", "Erro", JOptionPane.ERROR_MESSAGE);
            lblApostila.setForeground(Color.red);
        } else {
            lblApostila.setForeground(Color.black);
        }
        if (cbCatis.getSelectedItem().equals("Selecione um Catis")) {
            JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Catis\"", "Erro", JOptionPane.ERROR_MESSAGE);
            lblCatis.setForeground(Color.red);
        } else {
            lblCatis.setForeground(Color.black);
        }
        if (txtQtdApostilas.getText().equals("") || txtQtdApostilas.getText().equals("0")) {
            JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Quantidade de Apostilas\"   ", "Erro", JOptionPane.ERROR_MESSAGE);
            lblQauntidadeApostilas.setForeground(Color.red);
        } else {
            lblQauntidadeApostilas.setForeground(Color.black);
        }

        if (txtDataEnvio.getText().equals("  /  /    ")) {
            JOptionPane.showMessageDialog(this, "Preencha todos os campos \"Data de envio\" ", "Erro", JOptionPane.ERROR_MESSAGE);
            lblDataEnvio.setForeground(Color.red);
        } else { lblDataEnvio.setForeground(Color.black);}
        if(btnGrupo_Periodo==null){
        JOptionPane.showMessageDialog(this, "Selecione um período de aula","ERRO",JOptionPane.ERROR_MESSAGE);
        }
       
}
    }//GEN-LAST:event_btnEntregarActionPerformed

    private void btnEntregarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnEntregarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
  btnEntregarActionPerformed(null);   }
    }//GEN-LAST:event_btnEntregarKeyPressed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened

    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
  try{
        Conexao.desconectar();
        System.out.println("Desconectado!");
}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Erro ao desconectar o banco"+ ex.getMessage(),"ERRO",JOptionPane.ERROR_MESSAGE);
}   
    }//GEN-LAST:event_formWindowClosed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {               
                    new EntregaApostila().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(EntregaApostila.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEntregar;
    private javax.swing.ButtonGroup btnGrupo_Periodo;
    private javax.swing.JButton btnVoltar;
    private javax.swing.JComboBox cbApostila;
    private javax.swing.JComboBox cbCatis;
    private javax.swing.JComboBox cbProfessor;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblApostila;
    private javax.swing.JLabel lblCatis;
    private javax.swing.JLabel lblDataEnvio;
    private javax.swing.JLabel lblManha;
    private javax.swing.JLabel lblNoite;
    private javax.swing.JLabel lblProfessor;
    private javax.swing.JLabel lblQauntidadeApostilas;
    private javax.swing.JLabel lblTarde;
    private javax.swing.JLabel lbl_periodo;
    private javax.swing.JRadioButton rdBtn_Noite;
    private javax.swing.JRadioButton rdBtn_Tarde;
    private javax.swing.JRadioButton rdBtn_manha;
    private javax.swing.JFormattedTextField txtDataEnvio;
    private javax.swing.JTextField txtQtdApostilas;
    // End of variables declaration//GEN-END:variables
}
